クラスのインスタンスを配列で管理します。100個でも簡潔なコードに。
p5.js oop
Learning OOP Object Oriented Programming
クラスの威力を発揮!100個のキャラをシンプルに管理できます。
クラスの配列
for (let i = 0; i < MAX; i++) {
objs.push(new Circle());
}たったこれだけで100個の円を作成。
103(変数ベース配列)との比較
| 103 | 302 |
|---|---|
| 5つの配列を管理 | 1つの配列でOK |
| 初期化が複雑 | new Circle() だけ |
| update関数で全変数を処理 | obj.update() |
draw()のシンプルさ
for (let obj of objs) {
obj.update();
obj.display();
}各オブジェクトが自分自身の処理を持っているので、呼び出すだけ。
次の課題
円だけでなく四角も追加したい場合は? → 継承(extends) を使います!
View Source Code
let W, H, PW, PH;
const PADDING_RATIO = 0.2;
const MAX_SPEED = 10;
let objs = [];
const MAX = 100
class Circle {
constructor() {
this.pos = {
x: random(width),
y: random(height),
};
this.speed = {
x: (Math.random() - 0.5) * MAX_SPEED,
y: (Math.random() - 0.5) * MAX_SPEED,
};
this.acceleration = 0.1;
}
update() {
this.pos.x += this.speed.x;
this.pos.y += this.speed.y;
if (this.pos.x < 0 + PW) {
this.speed.x += this.acceleration;
} else if (this.pos.x > W - PW) {
this.speed.x -= this.acceleration;
}
if (this.pos.y < 0 + PH) {
this.speed.y += this.acceleration;
} else if (this.pos.y > H - PH) {
this.speed.y -= this.acceleration;
}
}
display() {
stroke(0);
fill(0);
ellipse(this.pos.x, this.pos.y, 10, 10);
// text(["1:", Math.floor(this.pos.x), Math.floor(this.pos.y)], this.pos.x + 10, this.pos.y + 10);
}
}
// main
function setup() {
createCanvas((W = windowWidth), (H = windowHeight));
PW = W * PADDING_RATIO;
PH = H * PADDING_RATIO;
for (let i = 0; i < MAX; i++) {
objs.push(new Circle());
}
}
function draw() {
background(255);
for (let i = 0; i < objs.length; i++) {
const obj = objs[i];
obj.update();
}
for (let i = 0; i < objs.length; i++) {
const obj = objs[i];
obj.display();
}
}